<template>
  <el-container style="min-height: 100vh">
    <!-- 侧边栏导航 -->
    <el-aside width="200px" class="sidebar">
      <div class="sidebar-logo">
        <h2>商家管理系统</h2>
      </div>
      <el-menu
        default-active="merchant/manage"
        class="sidebar-menu"
        router
        :unique-opened="true"
      >
        <!-- 商家管理（当前页） -->
        <el-menu-item index="/merchant/manage">
          <span>商家管理</span>
        </el-menu-item>
        <!-- 餐品管理 -->
        <el-menu-item index="/merchant/dishes">
          <span>餐品管理</span>
        </el-menu-item>
        <!-- 对账申请 -->
        <el-menu-item index="/merchant/reconciliation">
          <span>对账申请</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 顶部导航栏（含退出按钮） -->
      <el-header class="header">
        <div class="header-title">商家管理</div>
        <el-button 
          type="default" 
          @click="handleLogout"
          class="logout-btn"
        >
          退出登录
        </el-button>
      </el-header>

      <!-- 页面内容 -->
      <el-main class="main-content">
        <div class="operation-bar">
          <el-button type="primary" @click="handleAdd">新增商家</el-button>
        </div>

        <!-- 商家列表表格 -->
        <el-table
          :data="merchantList"
          border
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column prop="merchantId" label="商家ID" align="center" />
          <el-table-column prop="name" label="商家名称" align="center" />
          <el-table-column prop="address" label="地址" align="center" />
          <el-table-column prop="contactPerson" label="联系人" align="center" />
          <el-table-column prop="phone" label="联系电话" align="center" />
          <el-table-column prop="status" label="状态" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.merchantId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增/编辑弹窗 -->
        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增商家' : '编辑商家'"
          width="500px"
        >
          <el-form
            ref="formRef"
            :model="form"
            :rules="formRules"
            label-width="100px"
          >
            <el-form-item label="商家ID" prop="merchantId" v-if="dialogType === 'add'">
              <el-input v-model="form.merchantId" placeholder="请输入商家ID" />
            </el-form-item>
            <el-form-item label="商家名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商家名称" />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="营业中" value="营业中" />
                <el-option label="休息中" value="休息中" />
                <el-option label="已关闭" value="已关闭" />
              </el-select>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
              <el-input v-model="form.password" type="password" placeholder="请输入初始密码" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import type { Merchant } from '@/types/index';
import type { ElForm } from 'element-plus';

const router = useRouter();

// 表格数据 - 明确Merchant类型
const merchantList = ref<Merchant[]>([]);

// 弹窗状态
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');

// 表单数据
const form = reactive<Partial<Merchant>>({
  merchantId: '',
  name: '',
  address: '',
  contactPerson: '',
  phone: '',
  status: '营业中',
  password: ''
});

// 表单验证规则
const formRules = reactive({
  merchantId: [{ required: true, trigger: 'blur', message: '请输入商家ID' }],
  name: [{ required: true, trigger: 'blur', message: '请输入商家名称' }],
  address: [{ required: true, trigger: 'blur', message: '请输入地址' }],
  contactPerson: [{ required: true, trigger: 'blur', message: '请输入联系人' }],
  phone: [{ required: true, trigger: 'blur', message: '请输入联系电话' }],
  status: [{ required: true, trigger: 'change', message: '请选择状态' }],
  password: [{ required: true, trigger: 'blur', message: '请输入初始密码' }]
});

const formRef = ref<InstanceType<typeof ElForm>>();

// 页面加载时获取本地模拟数据
onMounted(() => {
  merchantList.value = [
    {
      merchantId: 'M001',
      name: '阳光餐厅',
      address: '一号食堂一楼',
      contactPerson: '张三',
      phone: '13800138000',
      status: '营业中'
    },
    {
      merchantId: 'M002',
      name: '学子餐厅',
      address: '二号食堂二楼',
      contactPerson: '李四',
      phone: '13900139000',
      status: '营业中'
    },
    {
      merchantId: 'M003',
      name: '清真餐厅',
      address: '一号食堂二楼',
      contactPerson: '王五',
      phone: '13700137000',
      status: '休息中'
    }
  ];
});

// 打开新增弹窗
const handleAdd = () => {
  dialogType.value = 'add';
  formRef.value?.resetFields();
  Object.assign(form, {
    merchantId: '',
    name: '',
    address: '',
    contactPerson: '',
    phone: '',
    status: '营业中',
    password: ''
  });
  dialogVisible.value = true;
};

// 打开编辑弹窗（指定参数类型）
const handleEdit = (row: Merchant) => {
  dialogType.value = 'edit';
  Object.assign(form, { ...row });
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          if (merchantList.value.some(m => m.merchantId === form.merchantId)) {
            throw new Error('商家ID已存在');
          }
          merchantList.value.push(form as Merchant);
          ElMessage.success('新增成功');
        } else {
          const index = merchantList.value.findIndex(m => m.merchantId === form.merchantId);
          if (index !== -1) {
            merchantList.value[index] = { ...merchantList.value[index], ...form } as Merchant;
          }
          ElMessage.success('编辑成功');
        }
        dialogVisible.value = false;
      } catch (error: any) {
        ElMessage.error(error.message || (dialogType.value === 'add' ? '新增失败' : '编辑失败'));
      }
    }
  });
};

// 删除商家（指定参数类型）
const handleDelete = async (merchantId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除该商家吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    merchantList.value = merchantList.value.filter(m => m.merchantId !== merchantId);
    ElMessage.success('删除成功');
  } catch (error) {
    // 取消删除不处理
  }
};

// 退出登录功能
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    router.push('/login');
    ElMessage.success('退出成功');
  } catch (error) {
    // 取消退出不处理
  }
};
</script>

<style scoped>
.sidebar {
  background-color: #f5f7fa;
  border-right: 1px solid #e5e7eb;
}
.sidebar-logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #e5e7eb;
}
.sidebar-logo h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}
.sidebar-menu {
  margin-top: 10px;
}
.sidebar-menu .el-menu-item.is-active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  border-bottom: 1px solid #e5e7eb;
  height: 60px;
}
.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.logout-btn {
  border-color: #ff4d4f;
  color: #ff4d4f;
}

.main-content {
  padding: 20px;
  background-color: #fff;
}
.operation-bar {
  margin-bottom: 10px;
}
</style>